import multer from "multer";
import path from "node:path";
import ctypto from "node:crypto";
import fs from "node:fs";
import fsp from "node:fs/promises";

let pathObj = {
  docsPath: path.join(process.cwd(), "upload/docs"),
  imagePath: path.join(process.cwd(), "upload/image"),
  mulicPath: path.join(process.cwd(), "upload/mulic"),
  videoPath: path.join(process.cwd(), "upload/video"),
  bigFile: path.join(process.cwd(), "uploads"),
};

function createStorage(type) {
  return multer.diskStorage({
    destination: (req, file, cb) => {
      if (type !== "bigFile") cb(null, pathObj[type]);
      else {
        let randomPath = Date.now() + ctypto.randomBytes(3).toString("hex");
        let bigDir = path.join(pathObj.bigFile, randomPath.toString("hex"));
        if (!fs.existsSync(bigDir)) fs.mkdirSync(bigDir);
        req.query.dirPath = bigDir;
        cb(null, bigDir);
      }
    },
    filename: (req, file, cb) => {
      let fileName = null;
      file.originalname = Buffer.from(file.originalname, "latin1").toString(
        "utf8"
      );
      if (type === "bigFile") {
        let randomPath = Date.now() + ctypto.randomBytes(3).toString("hex");
        fileName = `${randomPath}-${path.extname(file.originalname)}`;
      } else {
        fileName = `${req.body.index}-${file.originalname}`;
      }
      req.query.fileName = fileName;
      cb(null, fileName);
    },
  });
}


export const uploadDocs = multer({ storage: createStorage("docs") });
export const uploadImage = multer({ storage: createStorage("image") });
export const uploadMulic = multer({ storage: createStorage("mulic") });
export const uploadVideo = multer({ storage: createStorage("video") });
export const uploadBigFile = multer({ storage: createStorage("bigFile") });

export async function mergeFile(from, to) {
  let path = await fsp.readdir(from);
  path = path.sort((a, b) => a.split("-")[0] - b.split("-")[0]);
  for (let dir of path) {
    let data = await fsp.readFile(path.join(from, dir));
    await fsp.appendFile(to, data);
    await fsp.unlink(path.join(from, dir));
  }
  await fsp.rmdir(from);
}
